package com.gz.mylife.app;

import java.text.DecimalFormat;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.util.ToastUtils;
import com.gz.mylife.widget.LoadingCover;
import com.gz.mylife.widget.OfflineDialog;
import com.gz.mylife.widget.LoadingCover.OnLoadingCoverRefreshListener;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zl.smartmall.library.ISmartMall;
import com.zl.smartmall.library.listener.OrderConfirmationListener;
import com.zl.smartmall.library.listener.SubmitOrderListener;
import com.zl.smartmall.library.po.BuildingsInfo;
import com.zl.smartmall.library.po.DeliveryAddress;
import com.zl.smartmall.library.po.GroupsInfo;
import com.zl.smartmall.library.po.HousesInfo;
import com.zl.smartmall.library.po.InvoiceInfo;
import com.zl.smartmall.library.po.OrderCommoditiesInfo;
import com.zl.smartmall.library.po.OrderConfirmationInfo;
import com.zl.smartmall.library.po.PayInfo;
import com.zl.smartmall.library.po.SubmitOrderInfo;
import com.zl.smartmall.library.util.Constants;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.PreferenceModel;
import com.zl.smartmall.library.util.Tools;

public class OrderConfirmation extends BaseActivity implements OnLoadingCoverRefreshListener, OnClickListener, TextWatcher {
	
	private static final String TAG = OrderConfirmation.class.getSimpleName();
	private int mUseGoldCount;
	private int mPayType;
	private LayoutInflater mInflater;
	private OrderConfirmationListener mOrderConfirmationListener;
//	private SubmitOrderHttpHandler mSubmitHttpHandler;
	private InvoiceInfo mInvoiceModel;
	private OrderConfirmationInfo mOrderConfirmationModel;
	private SubmitOrderListener mSubmitOrderListener;
	
	private EditText mRemark;
	private LinearLayout mProductItemLayout;
	private LoadingCover mLoadingCover;
	private TextView mTotalPriceView;
	private TextView mAmount;
	private TextView mSumPrice;
	private TextView mFreight;
	private TextView mInvoiceHead;
	private TextView mInvoiceType;
	private TextView mPayName;
	private TextView mDelivery;
	private TextView mUserName;
	private TextView mUserPhone;
	private TextView mUserAddress;
	private TextView mSetupUserInfo;
	private EditText mEtSelectGoldCount;
	private TextView mTvTotalGoldCount;
	private TextView mTvMaxUseGoldCount;
	private TextView mTvUseGoldCount;
	private TextView mTvDeductionRMB;
	private Button mSubmit;
	private View mUserArrow;
	private OfflineDialog mOfflineDialog;
	private EditText mEtPhone;
	private EditText mEtReceiver;
	private TextView mTvHomeDelivery;
	private TextView mTvTakeSelf;
	private EditText maddress;//收货地址
	private Dialog mMenudialog;
	private TextView mTvTitle;
	private Dialog mLoadingData;
	private Button btn_change;//确认按钮
	private TextView group;
	private TextView building;
	private TextView house;
	private GroupsInfo groupsInfo;
	private BuildingsInfo buildingsInfo;
	private HousesInfo housesInfo;
	private int houseid=0;//房屋的id
	private String cmname;//小区名称

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_order_confirmation);
		
		mInflater = getLayoutInflater();
		initListener();
		
//		mActionBar.setTitle("订单确认");
		setActionbarTitle("订单确认", false);
		mLoadingCover = (LoadingCover) findViewById(R.id.layout_loading_cover);
		mLoadingCover.setOnLoadingCoverRefreshListener(this);
		mProductItemLayout = (LinearLayout) findViewById(R.id.layout_product_item);
		mTotalPriceView = (TextView) findViewById(R.id.amount_to_pay);
		mAmount = (TextView) findViewById(R.id.amount_to_pay_hint);
		mRemark = (EditText) findViewById(R.id.et_remark);
		mSumPrice = (TextView) findViewById(R.id.tv_sum_price);
		mFreight = (TextView) findViewById(R.id.tv_freight);
		mSubmit = (Button) findViewById(R.id.btn_submit);//提交订单按钮
		mSubmit.setClickable(false);
		mSubmit.setOnClickListener(this);
		mInvoiceHead = (TextView) findViewById(R.id.tv_invoice_head);
		mInvoiceType = (TextView) findViewById(R.id.tv_invoice_type);
		mPayName = (TextView) findViewById(R.id.tv_pay_head);
		mDelivery = (TextView) findViewById(R.id.tv_delivery);
		mUserAddress = (TextView) findViewById(R.id.tv_address);
		mUserName = (TextView) findViewById(R.id.tv_username);
		mUserPhone = (TextView) findViewById(R.id.tv_phone);
		mSetupUserInfo = (TextView) findViewById(R.id.tv_setup_receiver_info_hint);
		mUserArrow = findViewById(R.id.iv_receiver_arrow);
		mEtSelectGoldCount = (EditText) findViewById(R.id.tv_use_gold_count);
//		mEtSelectGoldCount.setText(String.valueOf(mUseGoldCount));
		mEtSelectGoldCount.addTextChangedListener(this);
		mEtSelectGoldCount.setHint(String.valueOf(mUseGoldCount));
//		mEtSelectGoldCount.setSelection(0);
		mTvTotalGoldCount = (TextView) findViewById(R.id.tv_total_gold);
		mTvMaxUseGoldCount =  (TextView) findViewById(R.id.tv_max_use_gold);
		mTvUseGoldCount = (TextView) findViewById(R.id.tv_use_gold);
		mTvDeductionRMB = (TextView) findViewById(R.id.tv_deduction_rmb);
		mOfflineDialog = (OfflineDialog) mInflater.inflate(R.layout.offline_dialog, null);
		mEtPhone = (EditText) findViewById(R.id.et_phone);//收货人电话
		mEtReceiver = (EditText) findViewById(R.id.et_receiver);//收货人
		maddress = (EditText) findViewById(R.id.et_receiver_address);//收货地址
		mTvHomeDelivery = (TextView) findViewById(R.id.tv_home_delivery);
		mTvHomeDelivery.setOnClickListener(this);
		mTvHomeDelivery.setTag(true);
		mTvTakeSelf = (TextView) findViewById(R.id.tv_take_self);
		mTvTakeSelf.setOnClickListener(this);
		mTvTakeSelf.setTag(false);
		findViewById(R.id.btn_decrease).setOnClickListener(this);
		findViewById(R.id.btn_increase).setOnClickListener(this);
		findViewById(R.id.layout_address).setOnClickListener(this);
		findViewById(R.id.layout_invoice_info).setOnClickListener(this);
		findViewById(R.id.layout_pay_delivery).setOnClickListener(this);
		mLoadingData = new Dialog(this, R.style.DialogTheme);
		mLoadingData.setContentView(R.layout.loading_data_dialog2);
		mLoadingData.setCancelable(false);
		mLoadingData.setCanceledOnTouchOutside(false);
		group = (TextView)findViewById(R.id.group);
		building = (TextView)findViewById(R.id.building);
		house = (TextView)findViewById(R.id.house);
		group.setOnClickListener(this);
		building.setOnClickListener(this);
		house.setOnClickListener(this);
		ISmartMall.getInstance().getOrderConfirmation(getIntent().getStringExtra("orderInfo"), mOrderConfirmationListener);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.order_confirmation, menu);
		return true;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (resultCode) {
		case Define.ACTIVITY_CODE_SETUP_INVOICE:
			mInvoiceHead.setText("发票抬头：" + data.getStringExtra("invoiceHead"));
//			mInvoiceHead.setTag(data.getStringExtra("invoiceHead"));
			mInvoiceType.setText("发票详情：" + data.getStringExtra("invoiceTypeName"));
//			mInvoiceType.setTag(data.getStringExtra("invoiceTypeName"));
			mInvoiceModel = new InvoiceInfo();
			mInvoiceModel.setInvoiceHead(data.getStringExtra("invoiceHead"));
			mInvoiceModel.setInvoiceTypeName(data.getStringExtra("invoiceTypeName"));
			break;
			
		case Define.ACTIVITY_CODE_PAY_DELIVERY:
			mDelivery.setText(data.getStringExtra("delivery"));
			mPayType = data.getIntExtra("payType", Define.PAY_TYPE_ONLINE_PAY);
			mPayName.setText(data.getStringExtra("payName"));
			break;
			
		case Define.ACTIVITY_CODE_ADD_RECEIVER_INFO:
			try {
				mOrderConfirmationModel.setDeliveryAddress(
						DeliveryAddress.parse(new JSONObject(data.getStringExtra("receiver"))));
				refreshUserLayout();
				
			} catch (JSONException e) {
				CrashHandler.e(e);
			}
			break;
			
		case Define.ACTIVITY_CODE_UPDATE_RECEIVER_INFO:
			try {
				mOrderConfirmationModel.setDeliveryAddress(
						DeliveryAddress.parse(new JSONObject(data.getStringExtra("consignee"))));
				refreshUserLayout();
				
			} catch (JSONException e) {
				CrashHandler.e(e);
			}
			break;
		case 100:
			Toast.makeText(this, data.getStringExtra("province"), Toast.LENGTH_SHORT).show();
			break;
		case 107:
			groupsInfo = data.getParcelableExtra("obj");
			String groupname = data.getStringExtra("groupname");
			group.setText(groupname);
			maddress.setText(cmname+" "+groupname);
			building.setText("");
			house.setText("");
			break;	
		case 108:
			buildingsInfo = (BuildingsInfo) data.getSerializableExtra("obj1");
			building.setText(buildingsInfo.getName());
			maddress.setText(cmname+" "+group.getText()+" "+buildingsInfo.getName());
			house.setText("");
			break;
		case 106:
			housesInfo = (HousesInfo) data.getSerializableExtra("obj");
			house.setText(housesInfo.getHouseaddress());
			houseid = housesInfo.getId();
			maddress.setText(cmname+" "+group.getText()+" "+buildingsInfo.getName()+" "+housesInfo.getHouseaddress());
			break;	

		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.layout_address:
			if(mOrderConfirmationModel.getDeliveryAddress() != null) {
				startActivityForResult(new Intent(getApplicationContext(), DeliveryAddressManager.class), Define.ACTIVITY_CODE_ADD_RECEIVER_INFO);
			}else {
//				Intent intent = new Intent(getApplicationContext(), SetupAddress.class);
//				intent.putExtra("isSelect", 1);
//				startActivityForResult(intent, Define.ACTIVITY_CODE_ADD_RECEIVER_INFO);
			}
//			startActivityForResult(new Intent(getApplicationContext(), NewAddressActivity.class), 0);
			break;
			
		case R.id.layout_invoice_info:
			startActivityForResult(new Intent(getApplicationContext(), SetupInvoice.class), 
					Define.ACTIVITY_CODE_SETUP_INVOICE);
			break;
			
		case R.id.btn_submit:          //点击提交订单的按钮
			//点击提交按钮判断收货地址的完成性
			if((!" ".equals(group.getText().toString())&&!group.getText().toString().isEmpty())&&(" ".equals(house.getText().toString())||house.getText().toString().isEmpty())) {
				Toast.makeText(getApplicationContext(), "请选择房屋信息", Toast.LENGTH_LONG).show();
			}else {
				createDialog();
			}
			
			break;
			
		case R.id.layout_pay_delivery:
			StringBuilder sbName = new StringBuilder();
			StringBuilder sbType = new StringBuilder();
			for(PayInfo payInfo : mOrderConfirmationModel.getPayInfos()) {
				sbType.append(payInfo.getPayType() + "_");
				sbName.append(payInfo.getPayName() + "_");
			}
			Intent intent = new Intent(getApplicationContext(), PayDelivery.class);
			intent.putExtra("payType", sbType.toString());
			intent.putExtra("payName", sbName.toString());
			startActivityForResult(intent, Define.ACTIVITY_CODE_PAY_DELIVERY);
			break;
			
		case R.id.btn_decrease:
			decreaseGold();
			break;
			
		case R.id.btn_increase:
			increaseGold();
			break;
			
		case R.id.tv_home_delivery:
			if(!(Boolean) mTvHomeDelivery.getTag()) {
				mTvHomeDelivery.setTag(true);
				mTvTakeSelf.setTag(false);
				Drawable drawable = getResources().getDrawable(R.drawable.ic_apply_exchange_checked);
				drawable.setBounds(0, 0, Tools.dip2px(getApplicationContext(), 14.5f), Tools.dip2px(getApplicationContext(), 14.5f));
				mTvHomeDelivery.setCompoundDrawables(drawable, null, null, null);
				drawable = getResources().getDrawable(R.drawable.ic_apply_exchange_unchecked);
				drawable.setBounds(0, 0, Tools.dip2px(getApplicationContext(), 14.5f), Tools.dip2px(getApplicationContext(), 14.5f));
				mTvTakeSelf.setCompoundDrawables(drawable, null, null, null);
				mTotalPriceView.setText("合计：￥" + new DecimalFormat("0.00").format(mOrderConfirmationModel.getTotalPrice() + mOrderConfirmationModel.getPostage()));
				mFreight.setText("配送费用: ￥" + new DecimalFormat("0.00").format(mOrderConfirmationModel.getPostage()));
			}
			break;
			
		case R.id.tv_take_self:
			if(!(Boolean) mTvTakeSelf.getTag()) {
				mTvTakeSelf.setTag(true);
				mTvHomeDelivery.setTag(false);
				Drawable drawable = getResources().getDrawable(R.drawable.ic_apply_exchange_checked);
				drawable.setBounds(0, 0, Tools.dip2px(getApplicationContext(), 14.5f), Tools.dip2px(getApplicationContext(), 14.5f));
				mTvTakeSelf.setCompoundDrawables(drawable, null, null, null);
				drawable = getResources().getDrawable(R.drawable.ic_apply_exchange_unchecked);
				drawable.setBounds(0, 0, Tools.dip2px(getApplicationContext(), 14.5f), Tools.dip2px(getApplicationContext(), 14.5f));
				mTvHomeDelivery.setCompoundDrawables(drawable, null, null, null);
				mTotalPriceView.setText("合计：￥" + new DecimalFormat("0.00").format(mOrderConfirmationModel.getTotalPrice()));
				mFreight.setText("配送费用: ￥" + new DecimalFormat("0.00").format(0));
			}
			break;
		case R.id.group:
			intent = new Intent();
			intent.setClass(getApplicationContext(), SelectGroupsActivity.class);
			intent.putExtra("cmid", mOrderConfirmationModel.getCmid());
			startActivityForResult(intent,107);
			break;
		case R.id.building:
			if(groupsInfo == null){
				Toast.makeText(this, "请先选择组团", Toast.LENGTH_SHORT).show();
				break;
			}
			intent = new Intent();
			intent.setClass(getApplicationContext(), SelectBuildingsActivity.class);
			intent.putExtra("groupid", groupsInfo.getId());
			startActivityForResult(intent,108);
			break;
		case R.id.house:
			if(buildingsInfo == null){
				Toast.makeText(this, "请先选择楼牌号", Toast.LENGTH_SHORT).show();
				break;
			}
			intent = new Intent();
			intent.setClass(getApplicationContext(), SelectHouseActivity.class);
			intent.putExtra("buildingid", buildingsInfo.getId());
			startActivityForResult(intent,106);
			break;
		}
	}

	@Override
	public void onLoadingCoverRefresh() {
		// TODO Auto-generated method stub
		ISmartMall.getInstance().getOrderConfirmation(getIntent().getStringExtra("orderInfo"), mOrderConfirmationListener);
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub
		CrashHandler.d(TAG, "beforeTextChanged" + " " + s);
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		String etGold = mEtSelectGoldCount.getText().toString();
		int inputGold = TextUtils.isEmpty(etGold) ? 0 : Integer.valueOf(etGold);
		if(inputGold > mOrderConfirmationModel.getTotalGold() ||
				inputGold > mOrderConfirmationModel.getMaxUseGold()) {
			int correctGold = mOrderConfirmationModel.getTotalGold() > mOrderConfirmationModel.getMaxUseGold() ?
					mOrderConfirmationModel.getMaxUseGold() : mOrderConfirmationModel.getTotalGold();
			mEtSelectGoldCount.setText(String.valueOf(correctGold));
			double ratio = correctGold * mOrderConfirmationModel.getGoldToMoneyRatio();
			DecimalFormat format = new DecimalFormat("0.00");
//			mTvUseGoldCount.setText("使用金豆 " + correctGold + ", 抵￥" + format.format(ratio));
			mTvDeductionRMB.setText("抵￥" + format.format(ratio));
			mTotalPriceView.setText("合计：￥" + format.format(mOrderConfirmationModel.getTotalPrice() - ratio));
				
		}else {
			double ratio = inputGold * mOrderConfirmationModel.getGoldToMoneyRatio();
			DecimalFormat format = new DecimalFormat("0.00");
//			mTvUseGoldCount.setText("使用金豆 " + inputGold + ", 抵￥" + format.format(ratio));
			mTvDeductionRMB.setText("抵￥" + format.format(ratio));
			mTotalPriceView.setText("合计：￥" + format.format(mOrderConfirmationModel.getTotalPrice() - ratio));
		}
		
		mEtSelectGoldCount.setSelection(mEtSelectGoldCount.getText().toString().length());

		CrashHandler.d(TAG, "onTextChanged");
	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub
		CrashHandler.d(TAG, "afterTextChanged");
		if("0".equals(s.toString())) {
			mEtSelectGoldCount.setText("");
		}
		
	}

	private void decreaseGold() {
		// TODO Auto-generated method stub
		int goldCount = Integer.valueOf(mEtSelectGoldCount.getText().toString());
		if(goldCount > 0) {
			goldCount--;
			double ratio = goldCount * mOrderConfirmationModel.getGoldToMoneyRatio();
			DecimalFormat format = new DecimalFormat("0.00");
			mEtSelectGoldCount.setText(String.valueOf(goldCount));
			mTvUseGoldCount.setText("使用" + Define.VOUCHER_NAME + goldCount + ", 抵￥" + format.format(ratio));
			mTotalPriceView.setText("合计：￥" + format.format(mOrderConfirmationModel.getTotalPrice() - ratio));
		}
	}
	
	private void increaseGold() {
		// TODO Auto-generated method stub
		int goldCount = Integer.valueOf(mEtSelectGoldCount.getText().toString());
		if(goldCount < mOrderConfirmationModel.getTotalGold() && 
				goldCount < mOrderConfirmationModel.getMaxUseGold()) {
			goldCount++;
			double ratio = goldCount * mOrderConfirmationModel.getGoldToMoneyRatio();
			DecimalFormat format = new DecimalFormat("0.00");
			mEtSelectGoldCount.setText(String.valueOf(goldCount));
			mTvUseGoldCount.setText("使用 " + Define.VOUCHER_NAME + goldCount + ", 抵￥" + format.format(ratio));
			mTotalPriceView.setText("合计：￥" + format.format(mOrderConfirmationModel.getTotalPrice() - ratio));
		}
	}
	
	private void initListener() {
		mOrderConfirmationListener = new OrderConfirmationListener() {
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshFailed();
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mOfflineDialog.show();
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshFailed();
			}
			
			@Override
			public void onNoMoreData() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshFailed("该商品暂时无法购买");
			}
			
			@Override
			public void onResponseSuccess(OrderConfirmationInfo orderConfirmationInfo) {
				// TODO Auto-generated method stub
				mOrderConfirmationModel = orderConfirmationInfo;
				initProductItemLayout(orderConfirmationInfo.getProductInfos());
				mAmount.setText("共" + orderConfirmationInfo.getProductInfos().size() + "件");
				mSumPrice.setText("￥" + new DecimalFormat("0.00").format(orderConfirmationInfo.getTotalPrice()));
				mTotalPriceView.setText("合计：￥" + new DecimalFormat("0.00").format(orderConfirmationInfo.getTotalPrice() + orderConfirmationInfo.getPostage()));
				mFreight.setText("配送费用: ￥" + new DecimalFormat("0.00").format(orderConfirmationInfo.getPostage()));
				SpannableString spanStr = new SpannableString("本订单可使用" + orderConfirmationInfo.getMaxUseGold() + Define.VOUCHER_NAME);
				spanStr.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.RGB_90C25B)),
						6, spanStr.length() - 2, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
				mTvMaxUseGoldCount.setText(spanStr);
				spanStr = new SpannableString("您的" + Define.VOUCHER_NAME + "数 " + orderConfirmationInfo.getTotalGold());
				spanStr.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.RGB_90C25B)),
						5, spanStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
				mTvTotalGoldCount.setText(spanStr);
				mSubmit.setClickable(true);
				
				houseid = orderConfirmationInfo.getHouseid();
				cmname = orderConfirmationInfo.getCmname();
//				if(model.getMaxUseGold() > 0 && model.getTotalGold() > 0) {
//					//有金豆并且商品也可以金豆抵扣
//					int correctGold = model.getTotalGold() > model.getMaxUseGold() ?
//							model.getMaxUseGold() : model.getTotalGold();
//					mEtSelectGoldCount.setText(String.valueOf(correctGold));
//					String etGold = mEtSelectGoldCount.getText().toString();
//					int inputGold = TextUtils.isEmpty(etGold) ? 0 : Integer.valueOf(etGold);
//					double ratio = inputGold * model.getGoldToMoneyRatio();
//					DecimalFormat format = new DecimalFormat("0.00");
//					mTvDeductionRMB.setText("抵￥" + format.format(ratio));
//					mTotalPriceView.setText("合计：￥" + format.format(model.getTotalPrice() - ratio));
//				}else {
					mTvDeductionRMB.setText("抵￥0.00");
//				}
					
				if(TextUtils.isEmpty(orderConfirmationInfo.getStoreHouse())) {
					mTvTakeSelf.setVisibility(View.GONE);
				
				}else {
					mTvTakeSelf.setVisibility(View.VISIBLE);
					mTvTakeSelf.setText("仓库自提(" + orderConfirmationInfo.getStoreHouse() + ")");
				}
				
				if(orderConfirmationInfo.getPayInfos().size() > 0) {
					mPayType = orderConfirmationInfo.getPayInfos().get(0).getPayType();
					mPayName.setText(orderConfirmationInfo.getPayInfos().get(0).getPayName());
				}
//				PayInfo payInfo = new PayInfo();
//				payInfo.setPayName("货到付款");
//				payInfo.setPayType(1);
//				orderConfirmationInfo.getPayInfos().add(payInfo);
				
				refreshUserLayout();
				mLoadingCover.onRefreshSuccess();
			}
		};
		
		mSubmitOrderListener = new SubmitOrderListener() {
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), "订单提交失败, 请重试", Toast.LENGTH_SHORT);
				mSubmit.setBackgroundResource(com.gz.mylife.R.drawable.btn_orange_selector);//订单提交失败按钮返回为原来的颜色
				
			}
			
			@Override
			public void onOffline() {//处于离线状态
				// TODO Auto-generated method stub
				mOfflineDialog.show();
				mSubmit.setBackgroundResource(com.gz.mylife.R.drawable.btn_orange_selector);//订单提交失败按钮返回为原来的颜色
			}
			
			@Override
			public void onNoNetWork() {//没有任何网络连接
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), Define.MSG_NO_NETWORK);
				mSubmit.setBackgroundResource(com.gz.mylife.R.drawable.btn_orange_selector);//订单提交失败按钮返回为原来的颜色
			}
			
			@Override
			public void onResponseSuccess(String orderCode) {
				// TODO Auto-generated method stub
				try {
					if (mPayName.getText().toString().trim().equals("在线支付")) {
						Intent intent = new Intent(getApplicationContext(), OrderDetail.class);
						intent.putExtra("sn", orderCode);
						startActivity(intent);
					}else {
						Intent intent = new Intent(getApplicationContext(), MyOrders.class);
						intent.putExtra("name", "我的订单");
						startActivity(intent);
					}
					int cartNum = PreferenceModel.getInt(Define.PREFERENCE_KEY_SHOPPING_CART_NUM, 0);
					PreferenceModel.putInt(Define.PREFERENCE_KEY_SHOPPING_CART_NUM, 
							cartNum - new JSONArray(getIntent().getStringExtra("orderInfo")).length());
					
					setResult(100);//刷新我的订单列表
					//通过广播刷新购物车
					Intent broastIntent = new Intent(Define.ACTION_REFRESH_SHOPPING_CART);
					sendBroadcast(broastIntent);
					finish();
				
				} catch (JSONException e) {
					CrashHandler.e(e);
				}
			}

			@Override
			public void onMultiMerchantFailed() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), "本订单含有多个供应商，请重新分别下单");
				mSubmit.setBackgroundResource(com.gz.mylife.R.drawable.btn_orange_selector);//订单提交失败按钮返回为原来的颜色
			}
			
		};
	}
	
	private void initProductItemLayout(List<OrderCommoditiesInfo> productInfos) {
		for(int i = 0; i < productInfos.size(); i++) {
			View root = mInflater.inflate(R.layout.order_confirmation_product_item, null);
			ImageView icon = (ImageView) root.findViewById(R.id.iv_product_icon);
			TextView price = (TextView) root.findViewById(R.id.tv_price);
			TextView num = (TextView) root.findViewById(R.id.tv_num);
			TextView intro = (TextView) root.findViewById(R.id.tv_product_intro);
			TextView shopName = (TextView) root.findViewById(R.id.tv_shop_name);
			price.setText("￥" + new DecimalFormat("0.00").format(productInfos.get(i).getPrice()));
			num.setText("x" + productInfos.get(i).getBuyNum());
			intro.setText(productInfos.get(i).getProductTitle());
			shopName.setText(productInfos.get(i).getShopName());
			ImageLoader.getInstance().displayImage(productInfos.get(i).getProductPicture(), icon);
			mProductItemLayout.addView(root);
			
//			if(i < productInfos.size() - 1) {
				View view = new View(this);
				mProductItemLayout.addView(view);
				view.setBackgroundResource(R.drawable.divider_deep);
				LinearLayout.LayoutParams params = (LayoutParams) view.getLayoutParams();
				params.width = android.view.ViewGroup.LayoutParams.MATCH_PARENT;
				params.height = Tools.dip2px(getApplicationContext(), 0.5f);
//			}
		}
	}

	private void refreshUserLayout() {
		if(mOrderConfirmationModel.getDeliveryAddress() != null) {
			mUserName.setText(mOrderConfirmationModel.getDeliveryAddress().getReceiver());
			mUserAddress.setText(mOrderConfirmationModel.getDeliveryAddress().getFullAddress());
			mUserPhone.setText(mOrderConfirmationModel.getDeliveryAddress().getPhone());
			mSetupUserInfo.setVisibility(View.GONE);
			mUserName.setVisibility(View.VISIBLE);
			mUserAddress.setVisibility(View.VISIBLE);
			mUserPhone.setVisibility(View.VISIBLE);
			mUserArrow.setVisibility(View.VISIBLE);
			
			String name = mOrderConfirmationModel.getDeliveryAddress().getReceiver();
			String newname ;
			if (name.length()-1==1) {
				newname = name.substring(0,name.length()-(name.substring(1)).length())+" *"+name.substring(name.length());
			}else {
				newname = name.substring(0,name.length()-(name.substring(1)).length())+" * *"+name.substring(name.length());
			}
			mEtReceiver.setText(newname);//默认的收货人姓名
			maddress.setText(mOrderConfirmationModel.getDeliveryAddress().getFullAddress());//默认的收货地址
			mEtPhone.setText(mOrderConfirmationModel.getDeliveryAddress().getPhone());//默认收货人的电话
			
		}else {
			mUserName.setVisibility(View.GONE);
			mUserAddress.setVisibility(View.GONE);
			mUserPhone.setVisibility(View.GONE);
			mUserArrow.setVisibility(View.GONE);
			mSetupUserInfo.setVisibility(View.VISIBLE);
		}
	}
	//提交订单的方法
	private void submitOrder() {
		
			JSONArray jsonArray = new JSONArray();
			for(OrderCommoditiesInfo info : mOrderConfirmationModel.getProductInfos()) {
				jsonArray.put(info.encodeJson());
			}
			byte[] enByte = Base64.encode(jsonArray.toString().getBytes(), Base64.DEFAULT);
			SubmitOrderInfo submitOrderInfo = new SubmitOrderInfo();
			submitOrderInfo.setPayType(String.valueOf(mPayType));//目前只有货到付款
			submitOrderInfo.setNation(mOrderConfirmationModel.getDeliveryAddress().getNation());
			submitOrderInfo.setProvince(mOrderConfirmationModel.getDeliveryAddress().getProvince());
			submitOrderInfo.setCity(mOrderConfirmationModel.getDeliveryAddress().getCity());
			submitOrderInfo.setDistrict(mOrderConfirmationModel.getDeliveryAddress().getDistrict());
			//submitOrderInfo.setAddress(mOrderConfirmationModel.getDeliveryAddress().getAddress());
			submitOrderInfo.setAddress(TextUtils.isEmpty(maddress.getText().toString()) ?mOrderConfirmationModel.getDeliveryAddress().getAddress() : maddress.getText().toString());
			submitOrderInfo.setPostcode(mOrderConfirmationModel.getDeliveryAddress().getPostcode());
			submitOrderInfo.setPhone(TextUtils.isEmpty(mEtPhone.getText().toString()) ? mOrderConfirmationModel.getDeliveryAddress().getPhone() : mEtPhone.getText().toString());
			submitOrderInfo.setReceiver(TextUtils.isEmpty(mEtReceiver.getText().toString()) ? mOrderConfirmationModel.getDeliveryAddress().getReceiver() :mEtReceiver.getText().toString());
			if((Boolean) mTvTakeSelf.getTag()) {
				submitOrderInfo.setDeliveryWay(Constants.TAKE_SELF);
				submitOrderInfo.setMoney(mOrderConfirmationModel.getTotalPrice());
				
			}else {
				submitOrderInfo.setDeliveryWay(Constants.PAY_ON_DELIVERY);
				submitOrderInfo.setMoney(mOrderConfirmationModel.getTotalPrice() + mOrderConfirmationModel.getPostage());
			}
			
			submitOrderInfo.setProducts(new String(enByte));
			submitOrderInfo.setDelivery((String) mDelivery.getText());
			submitOrderInfo.setRemark(mRemark.getText().toString());
			submitOrderInfo.setPostage(mOrderConfirmationModel.getPostage());
			if(mInvoiceModel != null) {
				submitOrderInfo.setInvoice(1);
				submitOrderInfo.setInvoiceHead(mInvoiceModel.getInvoiceHead());
				submitOrderInfo.setInvoiceTypeName(mInvoiceModel.getInvoiceTypeName());
				CrashHandler.d(TAG, "开发票");
				
			}else {
				submitOrderInfo.setInvoice(0);
				CrashHandler.d(TAG, "不开发票");
			}
			submitOrderInfo.setHouseid(houseid);
			
			ISmartMall.getInstance().submitOrder(submitOrderInfo, mSubmitOrderListener);
//			CrashHandler.d(TAG, "合计" + money + ", " + Define.VOUCHER_NAME + goldCount);

	}
	//点击提交订单的弹框确认
	private void createDialog() {
		mMenudialog = new Dialog(this, R.style.DialogTheme);
		View dialogView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.mycommunity_dialog_layout, null);
		mTvTitle = (TextView) dialogView.findViewById(R.id.tv_title);
		mTvTitle.setText("确认提交订单");
		btn_change = (Button) dialogView.findViewById(R.id.btn_change);
		btn_change.setText("确认");
		btn_change.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//mLoadingData.show();
				submitOrder();//点击确认调用提交订单的方法
				mSubmit.setBackgroundResource(com.gz.mylife.R.drawable.btn_gray_normal);//点击提交按钮之后将按钮的颜色变为灰色
				mMenudialog.dismiss();
				//mLoadingData.dismiss();
			}
		});
		dialogView.findViewById(R.id.btn_cancel).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mMenudialog.dismiss();
			}
		});
		mMenudialog.setContentView(dialogView);
		mMenudialog.setCancelable(false);
		mMenudialog.setCanceledOnTouchOutside(false);
		mMenudialog.show();
	}
	

}
